package cn.com.hhrcw.web;

import cn.com.hhrcw.entity.CvResume;
import cn.com.hhrcw.entity.CvUserEduInfo;
import cn.com.hhrcw.entity.File;
import cn.com.hhrcw.entity.PiInfo;
import cn.com.hhrcw.mapstruct.CvResumeAdminConvert;
import cn.com.hhrcw.params.CvResumeAdminParams;
import cn.com.hhrcw.service.ICvResumeService;
import cn.com.hhrcw.service.ICvUserEduInfoService;
import cn.com.hhrcw.service.IFileService;
import cn.com.hhrcw.service.IPiInfoService;
import cn.com.hhrcw.utils.IpUtils;
import cn.com.hhrcw.vo.CvResumeAdminVO;
import cn.com.hhrcw.vo.StringVO;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.function.Function;

/**
 * 简历-简历
 *
 * @author gaoruiyi
 * @since 2020-11-07
 */
@RestController
@Slf4j
@RequestMapping("/admin/cvResume")
@Api(tags = "简历-简历本历")
@Validated
public class CvResumeAdminController extends JeecgController<CvResume, ICvResumeService> {

    @Autowired
    private ICvResumeService cvResumeService;

    @Autowired
    private CvResumeAdminConvert cvResumeAdminConvert;

    @Autowired
    private IPiInfoService piInfoService;

    @Autowired
    private ICvUserEduInfoService cvUserEduInfoService;

    @Autowired
    private IFileService fileService;

    /**
     * 在线预览简历，二进制流形式
     *
     * @param userId   用户id
     * @param langType 语言类型0中文1英文
     * @param type     0在线简历1附件简历
     */
    @GetMapping("/getResumeBriny")
    @AutoLog(logType = 2, ty = "visit", value = "简历预览")
    public ResponseEntity getResumeBriny(String userId, Integer langType, Integer type,String jobId, HttpServletResponse response) throws IOException {
        String url = "";
        if (type != null && type == 1) {
            CvResume cvResume = service.lambdaQuery().eq(CvResume::getDelFlag, false).eq(CvResume::getUserId, userId)
                    .eq(CvResume::getType, 1).one();
            if (cvResume != null) {
                File file = fileService.getById(cvResume.getFileId());
                url = file.getFilePath();
            }
            java.io.File file = new java.io.File(url);
            byte[] bytes = new byte[0];
            if(file.exists()){
                bytes = FileUtil.readBytes(file);
            }
            return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_PDF)
                .contentLength(bytes.length)
                .body(new ByteArrayResource(bytes));
        } else {
            CvResume cvResume = service.lambdaQuery().eq(CvResume::getDelFlag, false).eq(CvResume::getUserId, userId)
                    .eq(CvResume::getType, 0).eq(CvResume::getLanType, langType).one();
            if (cvResume != null) {
                if (langType == 0) {
                    //中文
                    url = StringUtils.isNotBlank(cvResume.getPdfPath()) ? cvResume.getPdfPath() : service.getResumeInfoPDF(cvResume.getUserId(), 0,jobId);
                } else {
                    url = org.apache.commons.lang3.StringUtils.isNotBlank(cvResume.getPdfPathEn()) ? cvResume.getPdfPathEn() : service.getResumeInfoPDF(cvResume.getUserId(), 1, jobId);
                }
            }
            java.io.File file = new java.io.File(url);
            String html = file.exists() ? FileUtil.readString(file, StandardCharsets.UTF_8) : "";
            return ResponseEntity.ok()
                .contentType(MediaType.TEXT_HTML)
                .contentLength(file.length())
                .body(html);
        }
    }

    /**
     * 预览简历
     *
     * @param userId 用户id
     * @param type   简历类型0中文1英文
     * @return
     */
    @GetMapping("/getWordResume")
    @Deprecated
    public Result<StringVO> getResume(String userId, Integer type) {
        CvResume resume = cvResumeService.lambdaQuery().eq(CvResume::getDelFlag, false).
                eq(CvResume::getUserId, userId).eq(CvResume::getLanType, type).eq(CvResume::getType, 0).one();
        if (resume != null && StringUtils.isNotBlank(resume.getWordPath())) {
            return Result.ok(new StringVO(resume.getWordPath()));
        }
        String url = cvResumeService.getResumeInfoPDF(userId, type,null);
        return Result.ok(new StringVO(IpUtils.getIpAddress() + "/" + url));
    }

    /**
     * 查询所有用户简历接口
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/list")
    @AutoLog(logType = 2, ty = "visit", value = "查询简历列表")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    @PermissionData
    public Result<Page<CvResumeAdminVO>> list(CvResumeAdminParams params, HttpServletRequest request) {
        QueryWrapper<CvResume> queryWrapper = QueryGenerator.initQueryWrapper(cvResumeAdminConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByDesc("create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        IPage<CvResume> page = cvResumeService.page(params.page(), queryWrapper);
        //分页结果转换器
        Function<CvResume, CvResumeAdminVO> fun = cvResume -> {
            CvResumeAdminVO cvResumeAdminVO = cvResumeAdminConvert.toVO(cvResume);
            PiInfo piInfo = piInfoService.lambdaQuery()
                    .eq(PiInfo::getUserId, cvResume.getUserId())
                    .eq(PiInfo::getDelFlag, false)
                    .one();
            cvResumeAdminVO.setPiInfo(piInfo);
            CvUserEduInfo cvUserEduInfo = cvUserEduInfoService.lambdaQuery()
                    .eq(CvUserEduInfo::getUserId, cvResume.getUserId())
                    .eq(CvUserEduInfo::getDelFlag, false)
                    .one();
            cvResumeAdminVO.setCvUserEduInfo(cvUserEduInfo);

            BigDecimal deHistory = BigDecimal.valueOf(5
                   /* opDeliveryHistoryService.lambdaQuery()
                            .eq(OpDeliveryHistory::getDelFlag, false)
                            .eq(OpDeliveryHistory::getUserId, cvResume.getUserId())
                            .count()*/);

            BigDecimal inHistory = BigDecimal.valueOf(10
                    /*opInterviewHistoryService.lambdaQuery()
                            .eq(OpInterviewHistory::getDelFlag, false)
                            .eq(OpInterviewHistory::getUserId, cvResume.getUserId())
                            .count()*/);
            String deliveryRate = "0";
            if (inHistory.compareTo(BigDecimal.ZERO) != 0) {
                deliveryRate = deHistory.divide(inHistory, 2, BigDecimal.ROUND_HALF_UP).toString();
            }
            cvResumeAdminVO.setDeliveryRate(deliveryRate);

            return cvResumeAdminVO;
        };

        return Result.ok((Page) page.convert(fun));
    }

    /**
     * 违规禁用
     *
     * @param userId 数据userId
     * @return
     */
    @GetMapping(value = "/ban")
    @AutoLog(logType = 2, ty = "update", value = "简历违规禁用")
    @ApiOperation(value = "违规禁用", notes = "违规禁用")
    @RequiresPermissions("cvResume:edit")
    public Result ban(String userId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId, userId).one();
        piInfo.setBanFlag(piInfo.getBanFlag() == null || !piInfo.getBanFlag());
        piInfo.setUpdateBy(sysUser.getId());
        piInfo.setUpdateTime(new Date());
        boolean deleted = piInfoService.updateById(piInfo);
        return deleted ? Result.ok() : Result.error("禁用失败");
    }

    /**
     * 根据id查询
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/queryById")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    @PermissionData
    public Result<CvResumeAdminVO> queryById(String id) {
        CvResume cvResume = cvResumeService
                .lambdaQuery()
                .eq(CvResume::getId, id)
                .eq(CvResume::getDelFlag, false)
                .one();
        if (cvResume == null) {
            throw new JeecgBootException("数据不存在");
        }
        return Result.ok(cvResumeAdminConvert.toVO(cvResume));
    }

    /**
     * 添加
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/add")
    @AutoLog(logType = 2, ty = "insert", value = "添加简历")
    @ApiOperation(value = "添加", notes = "添加")
    @RequiresPermissions("cvResume:add")
    public Result<?> add(@RequestBody @Valid CvResumeAdminParams params) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        CvResume cvResume = cvResumeAdminConvert.toEntity(params);
        cvResume.setCreateBy(sysUser.getId());
        cvResume.setCreateTime(DateUtil.date());
        cvResume.setDelFlag(false);

        //cvResume.setNo(super.sort("cv_resume", Constant.NO_SEED));//FIXME: 编号,可根据情况隐藏
        boolean saved = cvResumeService.save(cvResume);
        return saved ? Result.ok() : Result.error("添加失败");
    }

    /**
     * 编辑
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/edit")
    @AutoLog(logType = 2, ty = "update", value = "修改简历")
    @ApiOperation(value = "编辑", notes = "编辑")
    @RequiresPermissions("cvResume:edit")
    public Result<?> edit(@RequestBody @Valid CvResumeAdminParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        CvResume cvResume = cvResumeAdminConvert.toEntity(params);
        cvResume.setUpdateBy(sysUser.getId());
        cvResume.setUpdateTime(DateUtil.date());

        boolean updated = cvResumeService.updateById(cvResume);
        return updated ? Result.ok() : Result.error("编辑失败");
    }


    /**
     * 批量删除
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/delete")
    @AutoLog(logType = 2, ty = "delete", value = "删除简历")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @RequiresPermissions("cvResume:delete")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaUpdateWrapper<CvResume> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(CvResume::getId, id)
                .set(CvResume::getDelFlag, true)
                .set(CvResume::getUpdateBy, sysUser.getUsername())
                .set(CvResume::getUpdateTime, DateUtil.date());

        boolean deleted = cvResumeService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    /**
     * 属性值是否重复
     *
     * @return
     */
    @Override
    @GetMapping("/propertyRepeat")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param params
     */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, CvResumeAdminParams params) {
        CvResume cvResume = cvResumeAdminConvert.toEntity(params);
        cvResume.setDelFlag(false);
        QueryWrapper<CvResume> queryWrapper = QueryGenerator.initQueryWrapper(cvResume, request.getParameterMap());
        List<CvResume> data = cvResumeService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("简历-简历本历", "简历-简历本历");
        String url = super.exportXls(exportParams, CvResumeAdminVO.class, cvResumeAdminConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CvResume.class);
    }



    /**
     * 查询用户简历接口
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/list2")
    @AutoLog(logType = 2, ty = "visit", value = "查询简历列表")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    @PermissionData
    public Result<IPage<CvResumeAdminVO>> list2(CvResumeAdminParams params, HttpServletRequest request) {

        QueryWrapper<CvResume> queryWrapper = QueryGenerator.initQueryWrapper(cvResumeAdminConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByAsc("lan_type");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        IPage<CvResume> page = cvResumeService.page(params.page(), queryWrapper);
        return Result.ok(page.convert(cvResumeAdminConvert::toVO));
    }

}
